﻿using Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using FastIM;

namespace WebApi.Controllers
{
    /// <summary>
    /// 即时聊天控制器websocket
    /// </summary>
    [Route("api/ws/")]
    [ApiController]
    public class WebSocketController : ControllerBase
    {

        public string Ip => this.Request.Headers["X-Forwarded-For"].FirstOrDefault() ?? this.Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

        /// <summary>
        /// 获取websocket地址。即时聊天之前必须调用本方法获取地址
        /// </summary>
        /// <param name="clientId">本地客户端标识，若无则不传，接口会返回新的，请保存本地localStoregy重复使用</param>
        /// <returns></returns>
        [HttpPost("pre-connect")]
        public Result<object> PreConnect([FromForm] string? clientId)
        {
            if (clientId == null)
            {
                //if (MyUser == null || MyUser.Id <= 0)
                // {
                clientId = "anony-" + new Random().Next(12);
                // }
                //else
                //{
                string type = "user";
                /*
                if ("teacher" == MyUser.Role)
                {
                    type = "teacher";
                }
                else if ("student" == MyUser.Role)
                {
                    type = "student";
                }*/
                // clientId = type + "-" + MyUser.Id;
                // }
            }
            var wsserver = ImHelper.PrevConnectServer(clientId, new FastIM.ClientMetaData { IP = Ip });
            return Result<object>.Success("succeed").SetData(new
            {
                server = wsserver,
                clientId
            });
        }

        /// <summary>
        /// 群聊，获取群列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("get-channels")]
        //[Authorize]
        public Result<object> GetChannels()
        {
            return Result<object>.Success("succeed").SetData(new
            {
                channels = ImHelper.GetChanList().Select(a => new { a.chan, a.online })
            });
        }
        /// <summary>
        /// 获取群聊频道的在线人数
        /// </summary>
        /// <param name="chan">群聊频道名</param>
        /// <returns>在线人数</returns>
        [HttpPost("get-channelonline-count")]
        public Result<object> GetChanOnline(string chan)
        {
            return Result<object>.Success("succeed").SetData(ImHelper.GetChanOnline(chan));
        }
        /// <summary>
        /// 获取所在线客户端id列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("get-clientlist-byonline")]
        public Result<object> GetClientListByOnline()
        {
            return Result<object>.Success("succeed").SetData(ImHelper.GetClientListByOnline());
        }
        /// <summary>
        /// 群聊，绑定消息频道。加入频道
        /// </summary>
        /// <param name="token">登录消息token。此token通过调用PreConnect方法接口返回的url获得</param>
        /// <param name="channel">消息频道</param>
        /// <returns></returns>
        [HttpPost("join-channel")]
        public Result<object> JoinChannel([FromForm] string channel, [FromForm] string token)
        {
            var logininfo = ImHelper.GetLoginInfo(token);
            if (logininfo.clientId == null)
            {
                return Result<object>.Error("请先通过PreConnect接口获取token");
            }
            else
            {
                ImHelper.JoinChan(logininfo.clientId, channel);
                return Result<object>.Success("succeed");
            }
        }
        /// <summary>
        /// 退出频道
        /// </summary>
        /// <param name="token">登录消息token。此token通过调用PreConnect方法接口返回的url获得</param>
        /// <param name="channel"></param>
        /// <returns></returns>
        [HttpPost("leave-channel")]
        public Result<object> LeaveChan([FromForm] string channel, [FromForm] string token)
        {
            var logininfo = ImHelper.GetLoginInfo(token);
            if (logininfo.clientId == null)
            {
                return Result<object>.Error("请先通过PreConnect接口获取token");
            }
            else
            {
                ImHelper.LeaveChan(logininfo.clientId, channel);
                return Result<object>.Success("succeed");
            }
        }

        /// <summary>
        /// 群聊，发送频道消息，绑定频道的所有人将收到消息
        /// </summary>
        /// <param name="channel">消息频道</param>
        /// <param name="msg">发送的消息具体内容，不必带有发送消息客户端id，接收消息客户端id</param>
        /// <param name="token">登录消息token。此token通过调用PreConnect方法接口返回的url获得</param>
        /// <returns></returns>
        [HttpPost("send-channelmsg")]
        public async Task<Result<object>> SendChannelmsg([FromForm] string channel, [FromForm] string msg , [FromForm] string token, [FromForm] string? msgId = null)
        {
            var logininfo = ImHelper.GetLoginInfo(token);
            if (logininfo.clientId == null)
            {
                return Result<object>.Error("请先通过PreConnect接口获取token");
            }
            else
            {
                await ImHelper.SendChanMessage(logininfo.clientId, channel, msg,logininfo.clientMetaData,msgId);
                return Result<object>.Success("succeed");
            }
        }
        /// <summary>
        /// 单聊
        /// </summary>
        /// <param name="receiveclientId">接收者</param>
        /// <param name="msg">发送的消息具体内容，不必带有发送消息客户端id，接收消息客户端id</param>
        /// <param name="isReceipt">是否需要回执</param>
        /// <param name="token">登录消息token。此token通过调用PreConnect方法接口返回的url获得</param>
        /// <returns></returns>
        [HttpPost("send-msg")]
        public async Task<Result<object>> Sendmsg([FromForm] string receiveClientId, [FromForm] string msg, [FromForm] string token, [FromForm] bool isReceipt = false, [FromForm] string? msgId = null)
        {
            var logininfo = ImHelper.GetLoginInfo(token);
            if (logininfo.clientId == null)
            {
                return Result<object>.Error("请先通过PreConnect接口获取token");
            }
            else
            {
                //var loginUser = 发送者;
                //var recieveUser = User.Get(receiveclientId);

                //if (loginUser.好友 != recieveUser) throw new Exception("不是好友");

                await ImHelper.SendMessage(logininfo.clientId, new[] { receiveClientId }, msg, QualityOfServiceLevel.AtMostOnce, logininfo.clientMetaData, msgId);

                //loginUser.保存记录(msg);
                //recieveUser.保存记录(msg);

                return Result<object>.Success("succeed");
            }

        }
    }
}
